package com.alumni_circle.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class GetOpen {

    private static final String URL_PREFIX = "https://api.weixin.qq.com/sns/jscode2session?appid=wx018ee5f7049c1bc9&secret=c4af5824191d17ce827acade2ffd56a5&js_code=";
    private static final String URL_SUFFIX = "&grant_type=authorization_code";


    public static String sendGet(String code){
        String line="";//访问返回结果
        BufferedReader read=null;//读取访问结果
        try {
            String url = URL_PREFIX+code+URL_SUFFIX;
//            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx018ee5f7049c1bc9&secret=c4af5824191d17ce827acade2ffd56a5&js_code="+code+"&grant_type=authorization_code";
            System.out.println(url);
            //创建url
            URL realurl=new URL(url);
            //打开连接
            URLConnection connection=realurl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //建立连接
            connection.connect();
            // 获取所有响应头字段
            read = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            line = read.readLine();//循环读取
            if(line.contains("errcode")){
                return "errcode";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(read!=null){//关闭流
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        System.out.println(line);
        String openid = line.substring(line.lastIndexOf(":")+2,line.lastIndexOf("\""));
//        System.out.println(line);
        return openid;
    }
}